package businessCommonQuery

import (
	"encoding/json"
	"fmt"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/request"
	pbCommon "grpc.getaway.adminspro.padmins.com/pkg/proto/common"
	"reflect"
	"strconv"
	"strings"
)

func BuildByRequest(r request.RequestInterface) (*pbCommon.BusinessCommonQuery, *businessError.ErrorInfo) {

	businessCommonQuery := &pbCommon.BusinessCommonQuery{
		Filters: map[string]string{},
		Ops:     map[string]string{},
		Offset:  0,
		Limit:   0,
		Sort:    []string{},
	}

	filters := r.Params("filters", "")
	ops := r.Params("ops", "")
	sort := r.Params("sort", "")
	orderWay := strings.ToUpper(r.ParamsToString("order", "ASC"))

	if filters != "" {
		jsonFilters := map[string]interface{}{}
		if reflect.TypeOf(filters).Kind() == reflect.String {
			e := json.Unmarshal([]byte(filters.(string)), &jsonFilters)
			if e != nil {
				return nil, businessError.Error(businessError.ParamsInvalid.Code, "filters参数格式错误")
			}
		} else {
			jsonFilters = filters.(map[string]interface{})
		}
		for s, i := range jsonFilters {
			businessCommonQuery.Filters[s] = fmt.Sprintf("%v", i)
		}
	}

	if ops != "" {
		if reflect.TypeOf(ops).Kind() == reflect.String {
			e := json.Unmarshal([]byte(ops.(string)), &businessCommonQuery.Ops)
			if e != nil {
				return nil, businessError.Error(businessError.ParamsInvalid.Code, "ops参数格式错误")
			}
		} else {
			businessCommonQuery.Ops = ops.(map[string]string)
		}
	}

	if orderWay != "ASC" && orderWay != "DESC" {
		return nil, businessError.Error(businessError.ParamsInvalid.Code, "order参数非法")
	}

	if sort != "" {
		if reflect.TypeOf(sort).Kind() == reflect.String {
			e := json.Unmarshal([]byte(sort.(string)), &businessCommonQuery.Sort)
			if e != nil {
				businessCommonQuery.Sort = append(businessCommonQuery.Sort, fmt.Sprintf("%s-%s", sort.(string), orderWay))
			}
		} else {
			if reflect.TypeOf(sort).Kind() != reflect.Slice {
				return nil, businessError.Error(businessError.ParamsInvalid.Code, "order参数非法")
			}
			businessCommonQuery.Sort = sort.([]string)
		}
	}

	sLimit := r.ParamsToString("limit", "10")

	nLimit := int64(0)
	if sLimit != "false" {
		nLimit, _ = strconv.ParseInt(sLimit, 10, 64)
		if nLimit <= 0 {
			nLimit = 10
		}
	}
	nOffset, _ := strconv.ParseInt(r.ParamsToString("offset", "0"), 10, 64)

	businessCommonQuery.Limit = nLimit
	businessCommonQuery.Offset = nOffset
	return businessCommonQuery, nil
}
